package com.vencent.spring.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.vencent.spring.exception.StudentsNotFountException;
import com.vencent.spring.model.Students;

/**
 * show how to handle exception.
 * @author 1d
 *
 */
@Controller
@RequestMapping("/students")
public class StudentController {
	@RequestMapping(value="/save", method = RequestMethod.GET)
	public String saveStudent(Students stu){
		try{
			save(stu);
			return "home";
		}catch(StudentsNotFountException e){
			return "error/students";
		}
	}
	
	private void save(Students stu) {
		if("Wang".equals(stu.getName())){
			throw new StudentsNotFountException();
		}
	}
	
	/**
	 * it can handle the same exception in this Controller.
	 * @return
	 */
	@ExceptionHandler(StudentsNotFountException.class)
	public String handlDuplicateStudent(){
		return "error/students";
	}
	
	/**
	 * use the @ExceptionHandler , you can use the following manner
	 * this way you can handle the same controller's different method.
	 * @param stu
	 * @return
	 */
	@RequestMapping(value="/save2", method = RequestMethod.GET)
	public String saveStudent2(Students stu){
		save(stu);
		return "home";
	}
}
